let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const users_router = require('./routes/users');
const post_router = require('./routes/post');
const user_message = require('./routes/user_message');

let app = express();

// 输出所有请求的日志
app.use(function (req, res, next) {
    req.time = new Date();
    // console.log(`${req.connection.remoteAddress} | ${req.headers['x-forwarded-for']} | ${req.originalUrl} | `);
    console.log(`${req.connection.remoteAddress} | ${req.time} | ${req.originalUrl} | `);
    next();
});

app.use(bodyParser.json({limit: '15mb'}));
app.use(bodyParser.urlencoded({limit: '15mb', extended: true}));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 挂载静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 动态路由
app.use('/users', users_router);
app.use('/post', post_router);
app.use('/user_message', user_message);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    // res.send('404 Not Found');
    res.status(404);
    res.statusMessage = '404 not found';
    res.sendFile(path.join(__dirname, '/views/error.html'))
});

module.exports = app;
